const fs = require('fs-extra');
const path = require('path');

/**
 * 依赖冲突解决器 - 处理复杂的版本冲突
 */
class DependencyResolver {
  constructor() {
    // 已知的依赖冲突解决方案
    this.conflictResolutions = {
      // Webpack版本冲突
      'webpack': {
        'sass-loader@8.0.0': { 'webpack': '^4.36.0' },
        'css-loader@2.1.1': { 'webpack': '^4.0.0' },
        'mini-css-extract-plugin@0.5.0': { 'webpack': '^4.4.0' },
        'url-loader@2.3.0': { 'webpack': '^4.0.0' }
      },
      // Vue CLI版本冲突
      'vue-cli': {
        '@vue/cli-service@5.0.8': { 'webpack-sources': '*' }
      },
      // 通用解决方案
      'general': {
        'node-sass': { 'sass': '^1.0.0' },
        'nodejieba': { 'skip': true },
        'fsevents': { 'skip': true }
      },
      // Sass冲突解决方案 (Vue2 uni-app专用)
      'sass': {
        'dart-sass': { 'remove': true, 'replace': 'node-sass@4.14.1' },
        'sass': { 'remove': true, 'replace': 'node-sass@4.14.1' },
        'sass-loader': { 'version': '^8.0.2' },
        'node-sass': { 'version': '4.14.1' }
      }
    };
  }

  /**
   * 分析并修复package.json中的依赖冲突
   */
  async resolveConflicts(projectPath) {
    const packagePath = path.join(projectPath, 'package.json');
    
    if (!await fs.pathExists(packagePath)) {
      return { resolved: false, message: 'package.json不存在' };
    }

    const pkg = await fs.readJson(packagePath);
    const originalPkg = JSON.parse(JSON.stringify(pkg)); // 深拷贝
    
    let changes = [];
    let resolved = false;

    // 1. 检测Webpack版本冲突
    const webpackVersion = this.getWebpackVersion(pkg);
    if (webpackVersion && webpackVersion.startsWith('5')) {
      changes = changes.concat(await this.resolveWebpack5Conflicts(pkg));
    }

    // 2. 处理已知问题依赖
    changes = changes.concat(await this.resolveKnownIssues(pkg));

    // 3. 可选的Sass冲突解决 (仅在明确需要时)
    // changes = changes.concat(await this.resolveSassConflicts(pkg)); // 注释掉，让项目自己处理

    // 4. 添加强制安装标志
    if (changes.length > 0) {
      await this.addForceInstallScripts(pkg);
      changes.push('添加强制安装脚本');
    }

    // 5. 保存修改
    if (changes.length > 0) {
      // 备份原始文件
      await fs.copy(packagePath, `${packagePath}.backup.${Date.now()}`);
      
      // 保存修改后的文件
      await fs.writeJson(packagePath, pkg, { spaces: 2 });
      
      resolved = true;
      console.log('🔧 依赖冲突修复完成:');
      changes.forEach(change => console.log(`  - ${change}`));
    }

    return { resolved, changes, originalPkg, modifiedPkg: pkg };
  }

  /**
   * 获取Webpack版本
   */
  getWebpackVersion(pkg) {
    const allDeps = { ...pkg.dependencies, ...pkg.devDependencies };
    return allDeps.webpack;
  }

  /**
   * 解决Webpack 5的兼容性问题
   */
  async resolveWebpack5Conflicts(pkg) {
    const changes = [];
    const allDeps = { ...pkg.dependencies, ...pkg.devDependencies };

    // 升级不兼容的loader到Webpack 5版本
    const webpack5Upgrades = {
      'sass-loader@8.0.0': 'sass-loader@^13.0.0',
      'css-loader@2.1.1': 'css-loader@^6.0.0',
      'mini-css-extract-plugin@0.5.0': 'mini-css-extract-plugin@^2.0.0',
      'url-loader@2.3.0': 'url-loader@^4.0.0'
    };

    for (const [oldDep, newDep] of Object.entries(webpack5Upgrades)) {
      const [name, version] = oldDep.split('@');
      if (allDeps[name] === version) {
        const [newName, newVersion] = newDep.split('@');
        
        if (pkg.devDependencies && pkg.devDependencies[name]) {
          pkg.devDependencies[name] = newVersion;
        } else if (pkg.dependencies && pkg.dependencies[name]) {
          pkg.dependencies[name] = newVersion;
        }
        
        changes.push(`升级 ${oldDep} → ${newDep}`);
      }
    }

    return changes;
  }

  /**
   * 解决已知问题依赖
   */
  async resolveKnownIssues(pkg) {
    const changes = [];
    const allDeps = { ...pkg.dependencies, ...pkg.devDependencies };

    // 替换node-sass为sass
    if (allDeps['node-sass']) {
      if (pkg.devDependencies && pkg.devDependencies['node-sass']) {
        delete pkg.devDependencies['node-sass'];
        pkg.devDependencies['sass'] = '^1.0.0';
      } else if (pkg.dependencies && pkg.dependencies['node-sass']) {
        delete pkg.dependencies['node-sass'];
        pkg.dependencies['sass'] = '^1.0.0';
      }
      changes.push('替换 node-sass → sass');
    }

    // 删除可选依赖
    const optionalDeps = ['nodejieba', 'fsevents'];
    for (const dep of optionalDeps) {
      if (allDeps[dep]) {
        if (pkg.devDependencies && pkg.devDependencies[dep]) {
          delete pkg.devDependencies[dep];
        } else if (pkg.dependencies && pkg.dependencies[dep]) {
          delete pkg.dependencies[dep];
        }
        changes.push(`删除可选依赖 ${dep}`);
      }
    }

    return changes;
  }

  /**
   * 添加强制安装脚本
   */
  async addForceInstallScripts(pkg) {
    if (!pkg.scripts) pkg.scripts = {};

    // 添加强制安装脚本
    pkg.scripts['install:force'] = 'npm install --legacy-peer-deps --force --ignore-optional --ignore-engines';
    pkg.scripts['install:clean'] = 'rm -rf node_modules package-lock.json && npm install --legacy-peer-deps';
    
    // 修改现有安装脚本
    if (pkg.scripts.install) {
      pkg.scripts.install = 'npm install --legacy-peer-deps --ignore-optional';
    }
  }

  /**
   * 生成.npmrc文件以强制解决冲突
   */
  async createNpmrc(projectPath) {
    const npmrcContent = `
# 强制解决依赖冲突
legacy-peer-deps=true
force=true
ignore-optional=true
ignore-engines=true
audit=false
fund=false

# 设置镜像源
registry=https://registry.npmmirror.com/
sass_binary_site=https://npmmirror.com/mirrors/node-sass/
phantomjs_cdnurl=https://npmmirror.com/mirrors/phantomjs/
electron_mirror=https://npmmirror.com/mirrors/electron/
sqlite3_binary_host_mirror=https://npmmirror.com/mirrors/
profiler_binary_host_mirror=https://npmmirror.com/mirrors/node-inspector/
chromedriver_cdnurl=https://npmmirror.com/mirrors/chromedriver

# 跳过可选依赖
optional=false
    `.trim();

    const npmrcPath = path.join(projectPath, '.npmrc');
    await fs.writeFile(npmrcPath, npmrcContent);
    
    console.log('📝 创建.npmrc配置文件');
    return npmrcPath;
  }

  /**
   * 生成.yarnrc文件
   */
  async createYarnrc(projectPath) {
    const yarnrcContent = `
# Yarn配置
ignore-optional true
ignore-engines true
network-timeout 300000

# 镜像源
registry "https://registry.npmmirror.com/"
sass_binary_site "https://npmmirror.com/mirrors/node-sass/"
phantomjs_cdnurl "https://npmmirror.com/mirrors/phantomjs/"
electron_mirror "https://npmmirror.com/mirrors/electron/"
    `.trim();

    const yarnrcPath = path.join(projectPath, '.yarnrc');
    await fs.writeFile(yarnrcPath, yarnrcContent);
    
    console.log('📝 创建.yarnrc配置文件');
    return yarnrcPath;
  }

  /**
   * 完整的依赖冲突解决流程
   */
  async resolveAllConflicts(projectPath) {
    try {
      console.log('🔍 开始分析依赖冲突...');
      
      // 1. 解决package.json中的冲突
      const resolution = await this.resolveConflicts(projectPath);
      
      // 2. 创建配置文件
      await this.createNpmrc(projectPath);
      await this.createYarnrc(projectPath);
      
      // 3. 清理可能的缓存
      const nodeModulesPath = path.join(projectPath, 'node_modules');
      if (await fs.pathExists(nodeModulesPath)) {
        console.log('🗑️  清理node_modules目录...');
        await fs.remove(nodeModulesPath);
      }
      
      const lockFiles = ['package-lock.json', 'yarn.lock', 'pnpm-lock.yaml'];
      for (const lockFile of lockFiles) {
        const lockPath = path.join(projectPath, lockFile);
        if (await fs.pathExists(lockPath)) {
          await fs.remove(lockPath);
          console.log(`🗑️  删除 ${lockFile}`);
        }
      }
      
      return {
        success: true,
        resolution,
        message: `依赖冲突解决完成，共修复 ${resolution.changes.length} 个问题`
      };
      
    } catch (error) {
      console.error('依赖冲突解决失败:', error);
      return {
        success: false,
        error: error.message
      };
    }
  }

  /**
   * 解决Sass相关冲突 (Vue2 uni-app专用)
   */
  async resolveSassConflicts(pkg) {
    const changes = [];
    
    // 检查是否是Vue2项目
    const vueVersion = pkg.dependencies?.vue || pkg.devDependencies?.vue;
    if (!vueVersion || !vueVersion.startsWith('^2.')) {
      return changes; // 非Vue2项目，跳过
    }

    console.log('🔧 检测到Vue2项目，解决Sass冲突...');

    // 移除 Dart Sass 相关包
    const sassPackagesToRemove = ['sass', 'dart-sass'];
    for (const packageName of sassPackagesToRemove) {
      if (pkg.dependencies?.[packageName]) {
        delete pkg.dependencies[packageName];
        changes.push(`移除dependencies中的${packageName}`);
      }
      if (pkg.devDependencies?.[packageName]) {
        delete pkg.devDependencies[packageName];
        changes.push(`移除devDependencies中的${packageName}`);
      }
    }

    // 确保使用正确版本的 node-sass
    if (!pkg.devDependencies) {
      pkg.devDependencies = {};
    }
    
    const targetNodeSassVersion = '4.14.1';
    if (!pkg.devDependencies['node-sass'] || pkg.devDependencies['node-sass'] !== targetNodeSassVersion) {
      pkg.devDependencies['node-sass'] = targetNodeSassVersion;
      changes.push(`设置node-sass版本为${targetNodeSassVersion}`);
    }

    // 确保使用兼容的 sass-loader 版本
    const targetSassLoaderVersion = '^8.0.2';
    if (pkg.devDependencies['sass-loader'] && !pkg.devDependencies['sass-loader'].startsWith('^8.')) {
      pkg.devDependencies['sass-loader'] = targetSassLoaderVersion;
      changes.push(`更新sass-loader版本为${targetSassLoaderVersion}`);
    }

    // 添加 Sass 强制配置到 package.json
    if (!pkg.config) {
      pkg.config = {};
    }
    
    if (!pkg.config.sass) {
      pkg.config.sass = {
        "implementation": "node-sass",
        "sassOptions": {
          "outputStyle": "expanded"
        }
      };
      changes.push('添加Sass强制配置');
    }

    return changes;
  }
}

module.exports = new DependencyResolver();
